package com.huilian.iotbox.admin.service.impl;


import com.huilian.iotbox.admin.dao.StatsAgencyDao;
import com.huilian.iotbox.admin.service.*;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.config.AgencyConfig;
import com.huilian.iotbox.data.dto.DeviceDto;
import com.huilian.iotbox.data.dto.MoneyDetailsDto;
import com.huilian.iotbox.data.dto.StatsAgencyDto;
import com.huilian.iotbox.data.dto.UserDto;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.po.Agency;
import com.huilian.iotbox.data.po.StatsAgency;
import com.huilian.iotbox.data.po.StatsUser;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.service.UserBalanceService;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.vo.DeviceVo;
import com.huilian.iotbox.data.vo.OrderVo;
import com.huilian.iotbox.data.vo.StatsAgencyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lizhiquan
 * @CreateDate: 2021-04-13 19:16
 * @Description:
 */
@Service
public class StatsAgencyServiceImpl implements StatsAgencyService {

    @Resource
    private StatsAgencyDao statsAgencyDao;
    @Autowired
    private MerchantStoreService merchantStoreService;
    @Autowired
    private AgencyService agencyService;
    @Autowired
    private StatsStoreService statsStoreService;
    @Autowired
    private StatsUserService statsUserService;
    @Autowired
    private UserBalanceService userBalanceService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private StatsDeviceService statsDeviceService;
    @Autowired
    private MoneyDetailsService moneyDetailsService;
    @Autowired
    private StatsMerchantService statsMerchantService;
    @Autowired
    private AgencyConfig agencyConfig;
    private static Integer TYPE_DAY = 1;
    private static Integer TYPE_MONTH = 2;

    @Override
    public Exception statsDayStoreAndAgencyJob() {
        //获取昨天 2022-09-22 00:00:00
        String startTime = DateTimeUtils.getYesterdayStartTime();
        //获取昨天 2022-09-22 23:59:59
        String endTime = DateTimeUtils.getYesterdayEndTime();
        //昨天日期
        String yesterday = DateTimeUtils.getYesterday();

        String currentDateStr = DateTimeUtils.getCurrentDateStr();

        Exception temp = null;
        try {
            // 统计每天商户的交易
            statsMerchantService.statsMerchantJob(startTime, endTime, yesterday, currentDateStr);

            // 统计前一天的设备数据
            statsDeviceService.statsDayDeviceJob(startTime, endTime, yesterday);
            // 统计前一天场地详细信息
            statsStoreService.statsStoreByMerchantStoreIdAndMemberIdJobV2(startTime, endTime, StatsTypeEnum.statsUser.getCode(), yesterday);
            // 统计前一天场地绑定设备详细信息
            statsStoreService.statsStoreByMerchantStoreIdAndMemberIdJobV2(startTime, endTime, StatsTypeEnum.onDeviceStatsUser.getCode(), yesterday);
            // 统计前一天运营商信息
            statsUserService.StatsDayUserJob(startTime, endTime, yesterday);

            //统计代理分润，必须场地统计好，再统计代理
            //莫总（改对应机构号）  机构为11155是莫总的
            if ("11155".equals(agencyConfig.getIsvOrgId())) {
                this.statsAgencyDaySettlementJobMo(startTime, endTime, yesterday);
            } else {
                //金总 机构为11156是金总的
                this.statsAgencyDaySettlementJobJin(startTime, endTime, yesterday);
            }

        } catch (Exception e) {
            e.printStackTrace();
            temp = e;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return temp;
    }

    @Override
    public void statsMonthAgencyJob(String startDateStr, String endDateStr) {
        List<StatsAgency> statsAgencyVoList = statsAgencyDao.findStatsAgencyList(startDateStr, endDateStr);
        String data = DateTimeUtils.getPreviousMonth();
        for (StatsAgency statsAgency : statsAgencyVoList) {
            statsAgency.setType(TYPE_MONTH);
            statsAgency.setDateStr(data);
            statsAgencyDao.insert(statsAgency);
        }
    }

    @Override
    public StatsAgencyVo findCountYesterday(StatsAgency statsAgency) {
        StatsAgencyVo countYesterday = statsAgencyDao.findCountYesterday(statsAgency);

        if(statsAgency.getUserInfo().getId().compareTo(172)==0){
            //定义50倍
            BigDecimal num = new BigDecimal(50);
            //昨天销售额 * 50
            countYesterday.setTurnover(countYesterday.getTurnover().multiply(num));
            //昨天交易币数 * 50
            countYesterday.setOrderCount(countYesterday.getOrderCount() * 50);
            //昨天利润 * 50
            countYesterday.setTotalCommission(countYesterday.getTotalCommission().multiply(num));
            //昨天销量 * 50
            countYesterday.setOutCoinTotal(countYesterday.getOutCoinTotal() * 50);
        }
        return countYesterday;
    }


    @Override
    public void statsAgencyDaySettlementJobMo(String startTime, String endTime, String yesterday) throws Exception {

        //统计代理一天分润
        List<StatsAgency> statsAgencyCommissionList = statsAgencyDao.statsAgencyDayCommission(startTime, endTime);

        //统计代理一天秒杀、拼团等订单分润
        List<StatsAgency> commissionActivityList = statsAgencyDao.statsAgencyDayCommissionByActivity(startTime, endTime);

        //统计状态正常代理数据
        List<Agency> agencyList = agencyService.findListByStatus(1);
        for (Agency agency : agencyList) {
//            if (agency.getId() == 1) {
//                continue;
//            }
            //统计代理一天营业额、订单数(下四级以内)
            Integer statsType = StatsTypeEnum.onDeviceStatsUser.getCode();
            StatsAgency statsAgencyData = statsAgencyDao.statsAgencyDayDataByAgencyId(agency.getId(), yesterday, statsType);
            statsAgencyData.setDateStr(yesterday);
            //代理当天分润
            BigDecimal totalCommission = BigDecimal.ZERO;

            BigDecimal activityTotalCommission = BigDecimal.ZERO;
            for (StatsAgency statsAgency : statsAgencyCommissionList) {
                if (agency.getId().equals(statsAgency.getAgencyId())) {
                    totalCommission = statsAgency.getTotalCommission();
                    break;
                }
            }
            for (StatsAgency statsAgency : commissionActivityList) {
                if (agency.getId().equals(statsAgency.getAgencyId())) {
                    activityTotalCommission = statsAgency.getTotalCommission();
                    break;
                }
            }
            statsAgencyData.setTotalCommission(totalCommission.add(activityTotalCommission));

            //统计代理当天新增场地数量
//            Integer num = merchantStoreService.findDayStoreNewNumByAgencyId(agency.getId(), startTime, endTime);
////            statsAgencyData.setStoreNewNum(num);
//            //获取昨天的订单信息
            List<OrderVo> orderVos = orderService.findDateOrder(agency.getId(), startTime, endTime);
//            // 场地Set
            Set<Integer> storeSet = new HashSet<>();
//
//            // 设备Set
            Set<String> deviceSet = new HashSet<>();
//            // 机构Set
            Set<Integer> agencySet = new HashSet<>();
            for (OrderVo orderVo : orderVos) {
                storeSet.add(orderVo.getMerchantStoreId());
                deviceSet.add(orderVo.getDeviceNo());
                agencySet.add(orderVo.getUserId());
            }
//            //1.统计场地无交易个数
            Integer storeNoTrade = merchantStoreService.findSetStoreNoTrade(agency.getId(), storeSet);
            statsAgencyData.setStoreNoTrade(storeNoTrade);
//            2.统计消费会员个数,3.统计会员新增个数
            statsAgencyData.setMemberNewNum(statsAgencyData.getMemberNewNum());
            statsAgencyData.setMemberConsumeNum(statsAgencyData.getMemberConsumeNum());
            //4.统计运营商新增个数
//            Integer userNewNum = userService.findNewOperatorsCount(agency.getId(), startTime, endTime);
//            statsAgencyData.setUserNewNum(userNewNum);
            //5.统计运营商无交易个数
            Integer userNoTrade = userService.findSetUserNoTrade(agency.getId(), agencySet);
            statsAgencyData.setUserNoTrade(userNoTrade);
            //6.统计设备新增个数
            DeviceDto deviceDto = new DeviceDto();
            deviceDto.setAgencyId(agency.getId());
            deviceDto.setStartTime(startTime);
            deviceDto.setEndTime(endTime);
            DeviceVo deviceVo = deviceService.findNewDeviceCount(deviceDto);
            statsAgencyData.setDeviceNewNum(deviceVo.getDeviceCount());
            //7.统计设备无交易个数
            Integer deviceNoTrade = deviceService.findSetDeviceNoTrade(agency.getId(), deviceSet);
            statsAgencyData.setDeviceNoTrade(deviceNoTrade);

            Integer count = statsAgencyDao.findStateAgencySubordinateDeal(yesterday, agency.getId());
            statsAgencyData.setAgencyNoTrade(count);
            //8.统计机构无交易个数
//            statsAgencyData.setAgencyNoTrade(agencyNoTrade);
            if (statsAgencyData.getTurnover() == null) {
                statsAgencyData.setTurnover(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverOnLine() == null) {
                statsAgencyData.setTurnoverOnLine(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverOffline() == null) {
                statsAgencyData.setTurnoverOffline(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverDouYin() == null) {
                statsAgencyData.setTurnoverDouYin(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverMeiTuan() == null) {
                statsAgencyData.setTurnoverMeiTuan(BigDecimal.ZERO);
            }
            if (statsAgencyData.getOrderCount() == null) {
                statsAgencyData.setOrderCount(0);
            }
            if (statsAgencyData.getOrderCountOnLine() == null) {
                statsAgencyData.setOrderCountOnLine(0);
            }
            if (statsAgencyData.getOrderCountOffline() == null) {
                statsAgencyData.setOrderCountOffline(0);
            }
            if (statsAgencyData.getCoinTotal() == null) {
                statsAgencyData.setCoinTotal(0);
            }
            statsAgencyData.setType(TYPE_DAY);
            statsAgencyData.setSettlementStatus(SettlementStatusEnum.COMPLETE.getCode());

            statsAgencyDao.insert(statsAgencyData);

            //代理分润自动确认增加余额
            if (agency.getId() != 13 && agency.getId() != 7 && agency.getId() != 1) {
                statsAgencyData.setUserId(agency.getUserId());
                this.money(statsAgencyData);
            }
        }


//        for (Agency agency : agencyList) {
//            if (agency.getId() == 1) {
//                continue;
//            }
//            Integer count = statsAgencyDao.findStateAgencySubordinateDeal(yesterday, agency.getId());
//            StatsAgency statsAgency = new StatsAgency();
//            statsAgency.setAgencyId(agency.getId());
//            statsAgency.setAgencyNoTrade(count);
//            statsAgency.setDateStr(yesterday);
//            statsAgencyDao.update(statsAgency);
//        }

        // 查询宏翔的分润
        StatsAgency statsTotalCommissionByHo = statsAgencyDao.getStatsAgencyByTotalCommission(yesterday, 13);
        // 查询汇联的分润
        StatsAgency statsTotalCommissionByHui = statsAgencyDao.getStatsAgencyByTotalCommission(yesterday, 7);
        // 宏翔的最总分润
        BigDecimal TotalCommissionByHo = statsTotalCommissionByHo.getTotalCommission().multiply(new BigDecimal(0.6))
                .add(statsTotalCommissionByHui.getTotalCommission().multiply(new BigDecimal(0.4)));
        // 汇联的最总分润
        BigDecimal TotalCommissionByHui = statsTotalCommissionByHo.getTotalCommission().multiply(new BigDecimal(0.4))
                .add(statsTotalCommissionByHui.getTotalCommission().multiply(new BigDecimal(0.6)));
        statsTotalCommissionByHo.setTotalCommission(TotalCommissionByHo);
        statsTotalCommissionByHui.setTotalCommission(TotalCommissionByHui);
        statsAgencyDao.update(statsTotalCommissionByHo);
        this.money(statsTotalCommissionByHo);
        statsAgencyDao.update(statsTotalCommissionByHui);
        this.money(statsTotalCommissionByHui);

        // 张总要求，超级管理员要加上汇联和宏翔的分润
        StatsAgency statsTotalCommission = statsAgencyDao.getStatsAgencyByTotalCommission(yesterday, 1);
        statsTotalCommission.setTotalCommission(statsTotalCommission.getTotalCommission().add(TotalCommissionByHui).add(TotalCommissionByHui));
        statsAgencyDao.update(statsTotalCommission);
        // 查看汇联与宏翔统计并从中统计出超级管理员的分润
//        StatsAgency statsAgency = statsAgencyDao.getStatsAgency(yesterday);
//        statsAgency.setAgencyId(1);
//        statsAgency.setDateStr(yesterday);
//        statsAgencyDao.insert(statsAgency);
    }

    // 增加分润余额
    private void money(StatsAgency statsAgencyData) throws Exception {
        if (statsAgencyData.getTotalCommission().compareTo(BigDecimal.ZERO) > 0) {
            UserDto userDto = new UserDto();
            userDto.setId(statsAgencyData.getUserId());
            userDto.setAddMoney(statsAgencyData.getTotalCommission());
            userDto.setMoneyType(MoneyTypeEnum.COMMISSION_BALANCE.getCode());
            User user = userBalanceService.addBalance(userDto, 0);
            // 资金明细
            MoneyDetailsDto moneyDetailsDto = new MoneyDetailsDto();
            moneyDetailsDto.setUserId(statsAgencyData.getUserId());
            moneyDetailsDto.setMoney(userDto.getAddMoney());
            moneyDetailsDto.setCashFlowType(1);
            moneyDetailsDto.setType(MoneyDetailsTypeEnum.BALANCE.getCode());
            moneyDetailsDto.setVoucherNo(String.valueOf(statsAgencyData.getAgencyId()));
            moneyDetailsDto.setBalance(user.getCommissionBalance());
            moneyDetailsDto.setRemark("佣金分润");
            moneyDetailsService.insert(moneyDetailsDto);
        }
    }

    @Override
    public void statsAgencyDaySettlementJobJin(String startTime, String endTime, String yesterday) throws Exception {
        //统计代理一天分润
        List<StatsAgency> statsAgencyCommissionList = statsAgencyDao.statsAgencyDayCommission(startTime, endTime);

        //统计代理一天秒杀、拼团等订单分润
        List<StatsAgency> commissionActivityList = statsAgencyDao.statsAgencyDayCommissionByActivity(startTime, endTime);


        //统计状态正常代理数据
        List<Agency> agencyList = agencyService.findListByStatus(1);
        for (Agency agency : agencyList) {
            //统计代理一天营业额、订单数(下三级以内)
            Integer statsType = StatsTypeEnum.onDeviceStatsUser.getCode();
            StatsAgency statsAgencyData = statsAgencyDao.statsAgencyDayDataByAgencyId(agency.getId(), yesterday, statsType);
            statsAgencyData.setDateStr(yesterday);
            //代理当天分润
            BigDecimal totalCommission = BigDecimal.ZERO;
            BigDecimal activityTotalCommission = BigDecimal.ZERO;
            for (StatsAgency statsAgency : statsAgencyCommissionList) {
                if (agency.getId().equals(statsAgency.getAgencyId())) {
                    totalCommission = statsAgency.getTotalCommission();
                    break;
                }
            }
            for (StatsAgency statsAgency : commissionActivityList) {
                if (agency.getId().equals(statsAgency.getAgencyId())) {
                    activityTotalCommission = statsAgency.getTotalCommission();
                    break;
                }
            }
            statsAgencyData.setTotalCommission(totalCommission.add(activityTotalCommission));

            //统计代理当天新增场地数量
            Integer num = merchantStoreService.findDayStoreNewNumByAgencyId(agency.getId(), startTime, endTime);
            statsAgencyData.setStoreNewNum(num);
//            //获取昨天的订单信息
            List<OrderVo> orderVos = orderService.findDateOrder(agency.getId(), startTime, endTime);
//            // 场地Set
            Set<Integer> storeSet = new HashSet<>();
//
//            // 设备Set
            Set<String> deviceSet = new HashSet<>();
//            // 机构Set
            Set<Integer> agencySet = new HashSet<>();
            for (OrderVo orderVo : orderVos) {
                storeSet.add(orderVo.getMerchantStoreId());
                deviceSet.add(orderVo.getDeviceNo());
                agencySet.add(orderVo.getUserId());
            }
//            //1.统计场地无交易个数
            Integer storeNoTrade = merchantStoreService.findSetStoreNoTrade(agency.getId(), storeSet);
            statsAgencyData.setStoreNoTrade(storeNoTrade);
            //2.统计消费会员个数,3.统计会员新增个数
            statsAgencyData.setMemberNewNum(statsAgencyData.getMemberNewNum());
            statsAgencyData.setMemberConsumeNum(statsAgencyData.getMemberConsumeNum());
            //4.统计运营商新增个数
            Integer userNewNum = userService.findNewOperatorsCount(agency.getId(), startTime, endTime);
            statsAgencyData.setUserNewNum(userNewNum);
            //5.统计运营商无交易个数
            Integer userNoTrade = userService.findSetUserNoTrade(agency.getId(), agencySet);
            statsAgencyData.setUserNoTrade(userNoTrade);
            //6.统计设备新增个数
            DeviceDto deviceDto = new DeviceDto();
            deviceDto.setAgencyId(agency.getId());
            deviceDto.setStartTime(startTime);
            deviceDto.setEndTime(endTime);
            DeviceVo deviceVo = deviceService.findNewDeviceCount(deviceDto);
            statsAgencyData.setDeviceNewNum(deviceVo.getDeviceCount());
            //7.统计设备无交易个数
            Integer deviceNoTrade = deviceService.findSetDeviceNoTrade(agency.getId(), deviceSet);
            statsAgencyData.setDeviceNoTrade(deviceNoTrade);
            //8.统计机构无交易个数
//            statsAgencyData.setAgencyNoTrade(agencyNoTrade);
            if (statsAgencyData.getTurnover() == null) {
                statsAgencyData.setTurnover(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverOnLine() == null) {
                statsAgencyData.setTurnoverOnLine(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverOffline() == null) {
                statsAgencyData.setTurnoverOffline(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverDouYin() == null) {
                statsAgencyData.setTurnoverDouYin(BigDecimal.ZERO);
            }
            if (statsAgencyData.getTurnoverMeiTuan() == null) {
                statsAgencyData.setTurnoverMeiTuan(BigDecimal.ZERO);
            }
            if (statsAgencyData.getOrderCount() == null) {
                statsAgencyData.setOrderCount(0);
            }
            if (statsAgencyData.getOrderCountOnLine() == null) {
                statsAgencyData.setOrderCountOnLine(0);
            }
            if (statsAgencyData.getOrderCountOffline() == null) {
                statsAgencyData.setOrderCountOffline(0);
            }
            if (statsAgencyData.getCoinTotal() == null) {
                statsAgencyData.setCoinTotal(0);
            }
            statsAgencyData.setType(TYPE_DAY);
            statsAgencyData.setSettlementStatus(SettlementStatusEnum.COMPLETE.getCode());

            statsAgencyDao.insert(statsAgencyData);

            //代理分润自动确认增加余额
            if (statsAgencyData.getTotalCommission().compareTo(BigDecimal.ZERO) > 0) {
                UserDto userDto = new UserDto();
                userDto.setId(agency.getUserId());
                userDto.setAddMoney(statsAgencyData.getTotalCommission());
                userDto.setMoneyType(MoneyTypeEnum.COMMISSION_BALANCE.getCode());
                User user = userBalanceService.addBalance(userDto, 0);

                MoneyDetailsDto moneyDetailsDto = new MoneyDetailsDto();
                moneyDetailsDto.setUserId(agency.getUserId());
                moneyDetailsDto.setMoney(userDto.getAddMoney());
                moneyDetailsDto.setCashFlowType(1);
                moneyDetailsDto.setType(MoneyDetailsTypeEnum.BALANCE.getCode());
                moneyDetailsDto.setVoucherNo(String.valueOf(statsAgencyData.getAgencyId()));
                moneyDetailsDto.setBalance(user.getCommissionBalance());
                moneyDetailsDto.setRemark("佣金分润");
                moneyDetailsService.insert(moneyDetailsDto);
            }
        }
        for (Agency agency : agencyList) {
            Integer count = statsAgencyDao.findStateAgencySubordinateDeal(yesterday, agency.getId());
            StatsAgency statsAgency = new StatsAgency();
            statsAgency.setAgencyId(agency.getId());
            statsAgency.setAgencyNoTrade(count);
            statsAgency.setDateStr(yesterday);
            statsAgencyDao.update(statsAgency);
        }
    }

    @Override
    public ServerResponse findList(StatsAgencyDto statsAgencyDto) {
        // 查询当前登录用户机构统计的数据
        List<StatsAgencyVo> statsAgencyList = new ArrayList<>();

        if (statsAgencyDto.getType().equals(1)) {
            statsAgencyDto.setStartDateStr(DateTimeUtils.formatByPattern(statsAgencyDto.getCreateTime(), "yyyy-MM-dd"));
            statsAgencyDto.setEndDateStr(DateTimeUtils.formatByPattern(statsAgencyDto.getUpdateTime(), "yyyy-MM-dd"));
        } else {
            statsAgencyDto.setStartDateStr(DateTimeUtils.formatByPattern(statsAgencyDto.getCreateTime(), "yyyy-MM"));
            statsAgencyDto.setEndDateStr(DateTimeUtils.formatByPattern(statsAgencyDto.getUpdateTime(), "yyyy-MM"));
        }


        if (statsAgencyDto.getUserInfo().getRoleId().equals(RoleEnum.FINANCE.getRoleId())) {
            List<StatsAgencyVo> agencyVoList = statsAgencyDao.findByFinanceAgency(statsAgencyDto);
            for (StatsAgencyVo a : agencyVoList) {
                StatsAgencyVo statsAgencyVo = this.getParentAgency(agencyVoList, a);
                if (!ObjectUtils.isEmpty(statsAgencyVo)) {
                    if (!statsAgencyList.contains(statsAgencyVo)) {
                        statsAgencyList.add(statsAgencyVo);
                    }
                }
            }
        } else {
            statsAgencyList = statsAgencyDao.findStatsAgency(statsAgencyDto);
        }

        List<StatsAgencyVo> statsAgencyVos = new ArrayList<>();

        // 查询当前登录账号能获取的机构统计数据
        for (StatsAgencyVo statsAgencyVo : statsAgencyList) {
            List<StatsAgencyVo> statsAgencyVoList = statsAgencyDao.findList(statsAgencyDto);
            // 递归获取下级数据
            List<StatsAgencyVo> topstatsAgencyVoList = statsAgencyVoList.stream().filter(item ->
                    item.getParentId().equals(statsAgencyVo.getAgencyId()) && item.getDateStr().equals(statsAgencyVo.getDateStr())
            ).map((item2) -> {
                item2.setChildren(getChildren(item2, statsAgencyVoList));
                return item2;
            }).collect(Collectors.toList());

            statsAgencyVo.setChildren(topstatsAgencyVoList);
            statsAgencyVos.add(statsAgencyVo);
        }
        return ServerResponse.createBySuccess(statsAgencyVos);
    }

    private StatsAgencyVo getParentAgency(List<StatsAgencyVo> list, StatsAgencyVo statsAgencyVo) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getAgencyId().equals(statsAgencyVo.getParentId())) {
                return this.getParentAgency(list, list.get(i));
            }
            if (i == list.size() - 1) {
                return statsAgencyVo;
            }
        }
        return null;
    }

    // 递归查找所有子机构、子商户
    private List<StatsAgencyVo> getChildren(StatsAgencyVo statsAgencyVo, List<StatsAgencyVo> statsAgencyVoList) {

        List<StatsAgencyVo> children = statsAgencyVoList.stream().filter(item -> {
            return item.getParentId().equals(statsAgencyVo.getAgencyId()) && item.getDateStr().equals(statsAgencyVo.getDateStr());
        }).map(item2 -> {
            // 找到子机构、子商户
            item2.setChildren(getChildren(item2, statsAgencyVoList));
            return item2;
        }).collect(Collectors.toList());

        return children;
    }

    @Override
    public List<StatsAgencyVo> findMonthlyTurnover(StatsAgencyDto statsAgencyDto) {
        switch (statsAgencyDto.getType()) {
            case 2:
                //数据库日期是yyyy-MM格式用yyyy-MM-ss 会导查询不对
                statsAgencyDto.setStartDateStr(this.getTheFirstMonth());
                statsAgencyDto.setEndDateStr(this.getsTheLastMonthOfThe());
                break;
            case 1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
                break;
            case -1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getPreviousMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getPreviousMonthLastDay());
                break;
        }
        //如果是管理员和机构登录就走这里
        List<StatsAgencyVo> list = new ArrayList<>();
        if (
                RoleEnum.SUPER_ADMINISTRATOR.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId()) ||
                        RoleEnum.AGENT.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId()) ||
                        RoleEnum.FINANCE.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId())) {
            list = statsAgencyDao.findMonthlyTurnover(statsAgencyDto);
        } else if (RoleEnum.MERCHANT.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId()) ||
                RoleEnum.SUB_ACCOUNT.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId())) {
            //如果是运营商登录子账号就走这里
            list = statsUserService.findMonthlyTurnover(statsAgencyDto);
        }

        if(statsAgencyDto.getUserInfo().getId().compareTo(172)==0){
            //定义50倍
            BigDecimal num = new BigDecimal(50);
            list.forEach(item->{
                item.setTurnover(item.getTurnover().multiply(num));
            });
        }
        return list;
    }
    private String getTheFirstMonth(){
        // 获取今年的第一个月的日期
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        Date firstDay = calendar.getTime();
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM");
        return  outputDateFormat.format(firstDay);
    }
    private String getsTheLastMonthOfThe(){
        // 获取今年的最后一个月的日期
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, Calendar.DECEMBER);
        Date firstDay = calendar.getTime();
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM");
        return  outputDateFormat.format(firstDay);
    }
    @Override
    public List<StatsAgencyVo> findMonthlyOrderCount(StatsAgencyDto statsAgencyDto) {
        switch (statsAgencyDto.getType()) {
            case 2:
                statsAgencyDto.setStartDateStr(this.getTheFirstMonth());
                statsAgencyDto.setEndDateStr(this.getsTheLastMonthOfThe());
                break;
            case 1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
                break;
            case -1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getPreviousMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getPreviousMonthLastDay());
                break;
        }
        //如果是管理员和机构登录就走这里
        List<StatsAgencyVo> list = new ArrayList<>();
        if (
                RoleEnum.SUPER_ADMINISTRATOR.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId()) ||
                        RoleEnum.AGENT.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId()) ||
                        RoleEnum.FINANCE.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId())) {
            list = statsAgencyDao.findMonthlyOrderCount(statsAgencyDto);
        } else if (RoleEnum.MERCHANT.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId())||
                RoleEnum.SUB_ACCOUNT.getRoleId().equals(statsAgencyDto.getUserInfo().getRoleId())) {
            //如果是运营商登录子账号就走这里
            list = statsUserService.findMonthlyTurnover(statsAgencyDto);
        }
        if(statsAgencyDto.getUserInfo().getId().compareTo(172)==0){
            list.forEach(item->{
                item.setOrderCount(item.getOrderCount() * 50);
            });
        }
        return list;
    }

    @Override
    public List<StatsAgencyVo> findMonthlyTotalCommission(StatsAgencyDto statsAgencyDto) {
        switch (statsAgencyDto.getType()) {
            case 2:
                statsAgencyDto.setStartDateStr(this.getTheFirstMonth());
                statsAgencyDto.setEndDateStr(this.getsTheLastMonthOfThe());
                break;
            case 1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
                break;
            case -1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getPreviousMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getPreviousMonthLastDay());
                break;
        }
        List<StatsAgencyVo> list = statsAgencyDao.findMonthlyTotalCommission(statsAgencyDto);
         if(statsAgencyDto.getUserInfo().getId().compareTo(172)==0){
             BigDecimal num = new BigDecimal(50);
            list.forEach(item->{
                item.setTotalCommission(item.getTotalCommission().multiply(num));
            });
        }
        return list;
    }


    @Override
    public List<StatsAgencyVo> findAgencyTotalCommissionTop(StatsAgencyDto statsAgencyDto) {
        if (statsAgencyDto.getType().equals(1)) {
            statsAgencyDto.setStartDateStr(DateTimeUtils.getYearFirstDay());
            statsAgencyDto.setEndDateStr(DateTimeUtils.getYearLastDay());
        } else {
            statsAgencyDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
            statsAgencyDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
        }
        List<StatsAgencyVo> list = statsAgencyDao.findAgencyTotalCommissionTop(statsAgencyDto);
        if(statsAgencyDto.getUserInfo().getId().compareTo(172)==0){
            BigDecimal num = new BigDecimal(50);
            list.forEach(item->{
                item.setTotalCommission(item.getTotalCommission().multiply(num));
            });
        }
        return list;
    }

    @Override
    public StatsAgencyVo findStateAgency(StatsAgencyDto statsAgencyDto) {
        switch (statsAgencyDto.getType()) {
            case 2:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getYesterday());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getYesterday());
                break;
            case 1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
                break;
            case -1:
                statsAgencyDto.setStartDateStr(DateTimeUtils.getPreviousMonthFirstDay());
                statsAgencyDto.setEndDateStr(DateTimeUtils.getPreviousMonthLastDay());
                break;
        }
        return statsAgencyDao.findStateAgency(statsAgencyDto);
    }
}
